import React, { useState, useEffect } from 'react'
import {
  Card,
  Row,
  Col,
  Statistic,
  Select,
  DatePicker,
  Space,
  Spin,
  Empty,
  Typography,
  Progress,
} from 'antd'
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts'
import {
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  DatabaseOutlined,
  TrendingUpOutlined,
} from '@ant-design/icons'
import { formatDuration, formatDateTime } from '@/utils'
import { getExecutionStats } from '@/services/executionAPI'

const { RangePicker } = DatePicker
const { Option } = Select
const { Text, Title } = Typography

interface ExecutionStatsData {
  total_executions: number
  successful_executions: number
  failed_executions: number
  average_duration: number
  total_duration: number
  most_used_connections: Array<{
    connection_id: string
    connection_name: string
    count: number
  }>
  execution_trends: Array<{
    date: string
    count: number
    avg_duration: number
    successful_count: number
    failed_count: number
  }>
}

interface ExecutionStatsProps {
  connectionId?: string
  onConnectionChange?: (connectionId?: string) => void
  connections?: Array<{
    id: string
    name: string
  }>
}

const ExecutionStats: React.FC<ExecutionStatsProps> = ({
  connectionId,
  onConnectionChange,
  connections = [],
}) => {
  const [loading, setLoading] = useState(false)
  const [statsData, setStatsData] = useState<ExecutionStatsData | null>(null)
  const [dateRange, setDateRange] = useState<[string, string] | null>(null)
  const [selectedConnection, setSelectedConnection] = useState<string | undefined>(connectionId)

  // 加载统计数据
  const loadStats = async () => {
    setLoading(true)
    try {
      const params: any = {}
      if (selectedConnection) {
        params.connection_id = selectedConnection
      }
      if (dateRange) {
        params.start_date = dateRange[0]
        params.end_date = dateRange[1]
      }

      const response = await getExecutionStats(params)
      if (response.success) {
        setStatsData(response.data)
      }
    } catch (error) {
      console.error('Failed to load execution stats:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadStats()
  }, [selectedConnection, dateRange])

  // 处理连接变更
  const handleConnectionChange = (value?: string) => {
    setSelectedConnection(value)
    onConnectionChange?.(value)
  }

  // 处理日期范围变更
  const handleDateRangeChange = (dates: any) => {
    if (dates && dates.length === 2) {
      setDateRange([
        dates[0].format('YYYY-MM-DD'),
        dates[1].format('YYYY-MM-DD'),
      ])
    } else {
      setDateRange(null)
    }
  }

  // 计算成功率
  const getSuccessRate = () => {
    if (!statsData || statsData.total_executions === 0) return 0
    return Math.round((statsData.successful_executions / statsData.total_executions) * 100)
  }

  // 图表颜色
  const COLORS = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1']

  if (loading && !statsData) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" />
        </div>
      </Card>
    )
  }

  if (!statsData) {
    return (
      <Card>
        <Empty description="暂无统计数据" />
      </Card>
    )
  }

  return (
    <div>
      {/* 过滤器 */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Space>
          <Select
            placeholder="选择连接"
            style={{ width: 200 }}
            value={selectedConnection}
            onChange={handleConnectionChange}
            allowClear
          >
            {connections.map(conn => (
              <Option key={conn.id} value={conn.id}>
                {conn.name}
              </Option>
            ))}
          </Select>
          
          <RangePicker
            placeholder={['开始日期', '结束日期']}
            onChange={handleDateRangeChange}
          />
        </Space>
      </Card>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总执行次数"
              value={statsData.total_executions}
              prefix={<DatabaseOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="成功执行"
              value={statsData.successful_executions}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
            <Progress
              percent={getSuccessRate()}
              size="small"
              strokeColor="#52c41a"
              showInfo={false}
              style={{ marginTop: 8 }}
            />
          </Card>
        </Col>
        
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="失败执行"
              value={statsData.failed_executions}
              prefix={<CloseCircleOutlined />}
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
        
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="平均耗时"
              value={formatDuration(statsData.average_duration)}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表 */}
      <Row gutter={[16, 16]}>
        {/* 执行趋势图 */}
        <Col xs={24} lg={16}>
          <Card title="执行趋势" size="small">
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={statsData.execution_trends}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date" 
                  tick={{ fontSize: 12 }}
                  tickFormatter={(value) => new Date(value).toLocaleDateString()}
                />
                <YAxis tick={{ fontSize: 12 }} />
                <Tooltip
                  labelFormatter={(value) => formatDateTime(value)}
                  formatter={(value: any, name: string) => {
                    if (name === 'avg_duration') {
                      return [formatDuration(value), '平均耗时']
                    }
                    return [value, name === 'count' ? '执行次数' : 
                            name === 'successful_count' ? '成功次数' : '失败次数']
                  }}
                />
                <Legend />
                <Line
                  type="monotone"
                  dataKey="count"
                  stroke="#1890ff"
                  strokeWidth={2}
                  name="执行次数"
                />
                <Line
                  type="monotone"
                  dataKey="successful_count"
                  stroke="#52c41a"
                  strokeWidth={2}
                  name="成功次数"
                />
                <Line
                  type="monotone"
                  dataKey="failed_count"
                  stroke="#f5222d"
                  strokeWidth={2}
                  name="失败次数"
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>

        {/* 连接使用统计 */}
        <Col xs={24} lg={8}>
          <Card title="连接使用统计" size="small">
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={statsData.most_used_connections}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ connection_name, percent }) => 
                    `${connection_name} ${(percent * 100).toFixed(0)}%`
                  }
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="count"
                >
                  {statsData.most_used_connections.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>

        {/* 性能趋势图 */}
        <Col xs={24}>
          <Card title="性能趋势" size="small">
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={statsData.execution_trends}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date" 
                  tick={{ fontSize: 12 }}
                  tickFormatter={(value) => new Date(value).toLocaleDateString()}
                />
                <YAxis tick={{ fontSize: 12 }} />
                <Tooltip
                  labelFormatter={(value) => formatDateTime(value)}
                  formatter={(value: any) => [formatDuration(value), '平均耗时']}
                />
                <Area
                  type="monotone"
                  dataKey="avg_duration"
                  stroke="#faad14"
                  fill="#faad14"
                  fillOpacity={0.3}
                />
              </AreaChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      {/* 连接详细统计 */}
      {statsData.most_used_connections.length > 0 && (
        <Card title="连接详细统计" size="small" style={{ marginTop: 16 }}>
          <Row gutter={[16, 16]}>
            {statsData.most_used_connections.map((conn, index) => (
              <Col xs={24} sm={12} md={8} lg={6} key={conn.connection_id}>
                <Card size="small">
                  <Statistic
                    title={conn.connection_name}
                    value={conn.count}
                    suffix="次"
                    valueStyle={{ 
                      color: COLORS[index % COLORS.length],
                      fontSize: 18,
                    }}
                  />
                  <div style={{ marginTop: 8 }}>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      占比: {((conn.count / statsData.total_executions) * 100).toFixed(1)}%
                    </Text>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        </Card>
      )}
    </div>
  )
}

export default ExecutionStats